#!/usr/bin/env python3
import sys
sys.path.append('/home/gd/dispatch-system/backend')

from wsgi import create_app
from app.models.user import User
from app.models import db
from flask_jwt_extended import decode_token
import jwt
from datetime import datetime
import os

app = create_app()
app.app_context().push()

print('=== 检查JWT配置 ===')
print(f'JWT_SECRET_KEY: {app.config.get("JWT_SECRET_KEY")}')
print(f'JWT_ALGORITHM: {app.config.get("JWT_ALGORITHM")}')
print(f'JWT_IDENTITY_CLAIM: {app.config.get("JWT_IDENTITY_CLAIM")}')

print('\n=== 测试创建和验证Token ===')
# 创建一个测试token
test_user = User.query.filter_by(username='admin').first()
if test_user:
    from flask_jwt_extended import create_access_token
    from datetime import timedelta
    
    test_token = create_access_token(
        identity=str(test_user.id),
        expires_delta=timedelta(hours=24)
    )
    print(f'测试用户: {test_user.username} (ID: {test_user.id})')
    print(f'生成的Token: {test_token[:50]}...')
    
    # 尝试解码token
    try:
        decoded = decode_token(test_token)
        print(f'Token解码成功: {decoded}')
    except Exception as e:
        print(f'Token解码失败: {e}')
        
    # 检查token是否过期
    try:
        payload = jwt.decode(test_token, app.config['JWT_SECRET_KEY'], algorithms=[app.config['JWT_ALGORITHM']])
        exp_timestamp = payload.get('exp')
        if exp_timestamp:
            exp_datetime = datetime.fromtimestamp(exp_timestamp)
            print(f'Token过期时间: {exp_datetime}')
            print(f'当前时间: {datetime.now()}')
            print(f'Token是否有效: {datetime.now() < exp_datetime}')
    except Exception as e:
        print(f'手动解码Token失败: {e}')
else:
    print('未找到admin用户')

print('\n=== 检查最近的认证日志 ===')
log_file = '/home/gd/dispatch-system/backend/backend.log'
if os.path.exists(log_file):
    with open(log_file, 'r') as f:
        lines = f.readlines()
        # 获取最后100行日志
        recent_lines = lines[-100:] if len(lines) > 100 else lines
        for line in recent_lines:
            if any(keyword in line.lower() for keyword in ['token', 'authorization', 'jwt', 'auth']):
                print(line.strip())
else:
    print('日志文件不存在')